<template>
  <div class="promotion-engine-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>促销规则引擎</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showRuleBuilder">
              <el-icon><Plus /></el-icon>
              新建规则
            </el-button>
            <el-button type="success" @click="testRules">
              <el-icon><Tools /></el-icon>
              测试规则
            </el-button>
            <el-button type="warning" @click="showRuleTemplate">
              <el-icon><Document /></el-icon>
              规则模板
            </el-button>
            <el-button type="info" @click="showRuleLogs">
              <el-icon><Clock /></el-icon>
              执行日志
            </el-button>
          </div>
        </div>
      </template>

      <!-- 规则引擎状态 -->
      <div class="engine-status">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="status-card">
              <div class="status-content">
                <div class="status-icon active">
                  <el-icon size="24"><Lightning /></el-icon>
                </div>
                <div class="status-info">
                  <div class="status-value">{{ engineStats.activeRules }}</div>
                  <div class="status-label">活跃规则</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="status-card">
              <div class="status-content">
                <div class="status-icon success">
                  <el-icon size="24"><Check /></el-icon>
                </div>
                <div class="status-info">
                  <div class="status-value">{{ engineStats.todayExecutions }}</div>
                  <div class="status-label">今日执行</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="status-card">
              <div class="status-content">
                <div class="status-icon warning">
                  <el-icon size="24"><Warning /></el-icon>
                </div>
                <div class="status-info">
                  <div class="status-value">{{ engineStats.errorCount }}</div>
                  <div class="status-label">错误次数</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="status-card">
              <div class="status-content">
                <div class="status-icon info">
                  <el-icon size="24"><Timer /></el-icon>
                </div>
                <div class="status-info">
                  <div class="status-value">{{ engineStats.avgResponseTime }}ms</div>
                  <div class="status-label">平均响应</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 规则列表 -->
      <div class="rules-section">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="促销规则" name="promotion">
            <div class="rules-header">
              <h4>促销规则列表</h4>
              <div class="rules-actions">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索规则..."
                  style="width: 200px;"
                  clearable
                >
                  <template #prepend>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-button type="primary" @click="refreshRules">刷新</el-button>
              </div>
            </div>
            
            <el-table :data="filteredRules" border stripe v-loading="loading">
              <el-table-column prop="id" label="规则ID" width="80" />
              <el-table-column prop="name" label="规则名称" width="200" />
              <el-table-column prop="type" label="规则类型" width="120">
                <template #default="{ row }">
                  <el-tag :type="getRuleTypeColor(row.type)">{{ getRuleTypeName(row.type) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="100" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusColor(row.status)">{{ getStatusName(row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="executionCount" label="执行次数" width="100" />
              <el-table-column prop="successRate" label="成功率" width="100">
                <template #default="{ row }">
                  <el-progress :percentage="row.successRate" :stroke-width="6" />
                </template>
              </el-table-column>
              <el-table-column prop="lastExecuted" label="最后执行" width="150" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewRule(row)">查看</el-button>
                  <el-button type="success" size="small" @click="editRule(row)">编辑</el-button>
                  <el-button 
                    :type="row.status === 'active' ? 'warning' : 'success'" 
                    size="small" 
                    @click="toggleRuleStatus(row)"
                  >
                    {{ row.status === 'active' ? '停用' : '启用' }}
                  </el-button>
                  <el-button type="danger" size="small" @click="deleteRule(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="规则测试" name="test">
            <div class="test-section">
              <el-form :model="testForm" label-width="120px">
                <el-form-item label="测试场景">
                  <el-select v-model="testForm.scenario" @change="handleScenarioChange" style="width: 100%">
                    <el-option label="满减活动测试" value="discount" />
                    <el-option label="买赠活动测试" value="gift" />
                    <el-option label="折扣活动测试" value="percentage" />
                    <el-option label="积分活动测试" value="points" />
                    <el-option label="会员专享测试" value="member" />
                    <el-option label="自定义测试" value="custom" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="购物车金额">
                  <el-input-number v-model="testForm.cartAmount" :min="0" :precision="2" style="width: 200px" />
                  <span class="form-tip">元</span>
                </el-form-item>
                
                <el-form-item label="商品数量">
                  <el-input-number v-model="testForm.itemCount" :min="1" style="width: 200px" />
                  <span class="form-tip">件</span>
                </el-form-item>
                
                <el-form-item label="客户类型">
                  <el-radio-group v-model="testForm.customerType">
                    <el-radio label="guest">普通客户</el-radio>
                    <el-radio label="member">会员客户</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item v-if="testForm.customerType === 'member'" label="会员等级">
                  <el-select v-model="testForm.memberLevel" style="width: 200px">
                    <el-option label="普通会员" value="normal" />
                    <el-option label="银卡会员" value="silver" />
                    <el-option label="金卡会员" value="gold" />
                    <el-option label="钻石会员" value="diamond" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="商品分类">
                  <el-select v-model="testForm.categories" multiple style="width: 100%">
                    <el-option label="电子产品" value="electronics" />
                    <el-option label="服装鞋帽" value="clothing" />
                    <el-option label="食品饮料" value="food" />
                    <el-option label="日用品" value="daily" />
                  </el-select>
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="executeTest" :loading="testLoading">执行测试</el-button>
                  <el-button @click="resetTestForm">重置</el-button>
                </el-form-item>
              </el-form>
              
              <div v-if="testResult" class="test-result">
                <el-divider>测试结果</el-divider>
                <el-card>
                  <div class="result-summary">
                    <h4>规则匹配结果</h4>
                    <p>匹配规则数: <strong>{{ testResult.matchedRules }}</strong></p>
                    <p>总优惠金额: <strong class="discount-amount">¥{{ testResult.totalDiscount.toFixed(2) }}</strong></p>
                    <p>最终支付金额: <strong class="final-amount">¥{{ testResult.finalAmount.toFixed(2) }}</strong></p>
                  </div>
                  
                  <div v-if="testResult.appliedRules.length > 0" class="applied-rules">
                    <h5>应用的规则:</h5>
                    <el-table :data="testResult.appliedRules" border size="small">
                      <el-table-column prop="name" label="规则名称" />
                      <el-table-column prop="type" label="类型" />
                      <el-table-column prop="discount" label="优惠金额">
                        <template #default="{ row }">¥{{ row.discount.toFixed(2) }}</template>
                      </el-table-column>
                      <el-table-column prop="description" label="说明" />
                    </el-table>
                  </div>
                </el-card>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="规则监控" name="monitor">
            <div class="monitor-section">
              <div class="monitor-controls">
                <el-form inline>
                  <el-form-item label="时间范围">
                    <el-date-picker
                      v-model="monitorForm.dateRange"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                    />
                  </el-form-item>
                  <el-form-item label="规则类型">
                    <el-select v-model="monitorForm.ruleType" placeholder="选择类型" clearable>
                      <el-option label="满减规则" value="discount" />
                      <el-option label="买赠规则" value="gift" />
                      <el-option label="折扣规则" value="percentage" />
                      <el-option label="积分规则" value="points" />
                      <el-option label="会员规则" value="member" />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="loadMonitorData">查询</el-button>
                    <el-button @click="resetMonitorForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>
              
              <div class="monitor-charts">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-card>
                      <template #header>
                        <span>规则执行趋势</span>
                      </template>
                      <div class="chart-placeholder">
                        <el-icon size="48"><TrendCharts /></el-icon>
                        <p>执行趋势图</p>
                      </div>
                    </el-card>
                  </el-col>
                  <el-col :span="12">
                    <el-card>
                      <template #header>
                        <span>规则成功率</span>
                      </template>
                      <div class="chart-placeholder">
                        <el-icon size="48"><PieChart /></el-icon>
                        <p>成功率饼图</p>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </div>
              
              <div class="monitor-table">
                <el-table :data="monitorData" border stripe>
                  <el-table-column prop="ruleName" label="规则名称" width="200" />
                  <el-table-column prop="executionTime" label="执行时间" width="180" />
                  <el-table-column prop="executionCount" label="执行次数" width="100" />
                  <el-table-column prop="successCount" label="成功次数" width="100" />
                  <el-table-column prop="errorCount" label="错误次数" width="100" />
                  <el-table-column prop="successRate" label="成功率" width="100">
                    <template #default="{ row }">
                      <el-progress :percentage="row.successRate" :stroke-width="6" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="avgResponseTime" label="平均响应时间" width="120">
                    <template #default="{ row }">{{ row.avgResponseTime }}ms</template>
                  </el-table-column>
                  <el-table-column prop="totalDiscount" label="总优惠金额" width="120">
                    <template #default="{ row }">¥{{ row.totalDiscount.toFixed(2) }}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <!-- 规则构建器对话框 -->
    <el-dialog
      v-model="ruleBuilderVisible"
      title="规则构建器"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="rule-builder">
        <el-tabs v-model="builderTab">
          <el-tab-pane label="规则配置" name="config">
            <el-form :model="ruleForm" :rules="ruleRules" ref="ruleFormRef" label-width="120px">
              <el-form-item label="规则名称" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
              </el-form-item>
              <el-form-item label="规则类型" prop="type">
                <el-select v-model="ruleForm.type" @change="handleRuleTypeChange" style="width: 100%">
                  <el-option label="满减规则" value="discount" />
                  <el-option label="买赠规则" value="gift" />
                  <el-option label="折扣规则" value="percentage" />
                  <el-option label="积分规则" value="points" />
                  <el-option label="会员规则" value="member" />
                </el-select>
              </el-form-item>
              <el-form-item label="规则描述" prop="description">
                <el-input v-model="ruleForm.description" type="textarea" :rows="3" placeholder="请输入规则描述" />
              </el-form-item>
              <el-form-item label="优先级" prop="priority">
                <el-input-number v-model="ruleForm.priority" :min="1" :max="100" style="width: 200px" />
                <span class="form-tip">数字越大优先级越高</span>
              </el-form-item>
              <el-form-item label="规则状态" prop="status">
                <el-radio-group v-model="ruleForm.status">
                  <el-radio label="active">启用</el-radio>
                  <el-radio label="inactive">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="条件配置" name="conditions">
            <div class="conditions-builder">
              <h4>规则条件</h4>
              <div class="condition-group">
                <div v-for="(condition, index) in ruleForm.conditions" :key="index" class="condition-item">
                  <el-row :gutter="10">
                    <el-col :span="6">
                      <el-select v-model="condition.field" placeholder="选择字段">
                        <el-option label="购物车金额" value="cartAmount" />
                        <el-option label="商品数量" value="itemCount" />
                        <el-option label="客户类型" value="customerType" />
                        <el-option label="会员等级" value="memberLevel" />
                        <el-option label="商品分类" value="category" />
                      </el-select>
                    </el-col>
                    <el-col :span="4">
                      <el-select v-model="condition.operator" placeholder="操作符">
                        <el-option label="等于" value="eq" />
                        <el-option label="不等于" value="ne" />
                        <el-option label="大于" value="gt" />
                        <el-option label="小于" value="lt" />
                        <el-option label="大于等于" value="gte" />
                        <el-option label="小于等于" value="lte" />
                        <el-option label="包含" value="in" />
                        <el-option label="不包含" value="not_in" />
                      </el-select>
                    </el-col>
                    <el-col :span="6">
                      <el-input v-model="condition.value" placeholder="条件值" />
                    </el-col>
                    <el-col :span="4">
                      <el-select v-model="condition.logic" placeholder="逻辑">
                        <el-option label="AND" value="and" />
                        <el-option label="OR" value="or" />
                      </el-select>
                    </el-col>
                    <el-col :span="4">
                      <el-button type="danger" size="small" @click="removeCondition(index)">删除</el-button>
                    </el-col>
                  </el-row>
                </div>
                <el-button type="primary" @click="addCondition">添加条件</el-button>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="动作配置" name="actions">
            <div class="actions-builder">
              <h4>规则动作</h4>
              <el-form :model="ruleForm.action" label-width="120px">
                <el-form-item label="动作类型">
                  <el-select v-model="ruleForm.action.type" @change="handleActionTypeChange" style="width: 100%">
                    <el-option label="减免金额" value="discount" />
                    <el-option label="赠送商品" value="gift" />
                    <el-option label="折扣比例" value="percentage" />
                    <el-option label="赠送积分" value="points" />
                    <el-option label="会员优惠" value="member" />
                  </el-select>
                </el-form-item>
                
                <el-form-item v-if="ruleForm.action.type === 'discount'" label="减免金额">
                  <el-input-number v-model="ruleForm.action.discountAmount" :min="0" :precision="2" style="width: 200px" />
                  <span class="form-tip">元</span>
                </el-form-item>
                
                <el-form-item v-if="ruleForm.action.type === 'percentage'" label="折扣比例">
                  <el-input-number v-model="ruleForm.action.discountRate" :min="1" :max="99" style="width: 200px" />
                  <span class="form-tip">折</span>
                </el-form-item>
                
                <el-form-item v-if="ruleForm.action.type === 'points'" label="赠送积分">
                  <el-input-number v-model="ruleForm.action.pointsAmount" :min="0" style="width: 200px" />
                  <span class="form-tip">分</span>
                </el-form-item>
                
                <el-form-item label="最大优惠">
                  <el-input-number v-model="ruleForm.action.maxDiscount" :min="0" :precision="2" style="width: 200px" />
                  <span class="form-tip">元（0表示不限制）</span>
                </el-form-item>
                
                <el-form-item label="动作描述">
                  <el-input v-model="ruleForm.action.description" type="textarea" :rows="2" placeholder="请输入动作描述" />
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <el-button @click="ruleBuilderVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRule" :loading="saveLoading">
          保存规则
        </el-button>
      </template>
    </el-dialog>

    <!-- 规则详情对话框 -->
    <el-dialog
      v-model="ruleDetailVisible"
      title="规则详情"
      width="700px"
    >
      <div v-if="currentRule" class="rule-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="规则名称">{{ currentRule.name }}</el-descriptions-item>
          <el-descriptions-item label="规则类型">
            <el-tag :type="getRuleTypeColor(currentRule.type)">{{ getRuleTypeName(currentRule.type) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">{{ currentRule.priority }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusColor(currentRule.status)">{{ getStatusName(currentRule.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行次数">{{ currentRule.executionCount }}</el-descriptions-item>
          <el-descriptions-item label="成功率">
            <el-progress :percentage="currentRule.successRate" :stroke-width="6" />
          </el-descriptions-item>
          <el-descriptions-item label="最后执行">{{ currentRule.lastExecuted }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentRule.createTime }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider>规则描述</el-divider>
        <p>{{ currentRule.description }}</p>
        
        <el-divider>规则条件</el-divider>
        <div class="conditions-display">
          <pre>{{ JSON.stringify(currentRule.conditions, null, 2) }}</pre>
        </div>
        
        <el-divider>规则动作</el-divider>
        <div class="actions-display">
          <pre>{{ JSON.stringify(currentRule.action, null, 2) }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const testLoading = ref(false)
const activeTab = ref('promotion')
const searchKeyword = ref('')
const ruleBuilderVisible = ref(false)
const ruleDetailVisible = ref(false)
const builderTab = ref('config')
const ruleFormRef = ref()

// 当前规则
const currentRule = ref(null)

// 引擎统计
const engineStats = reactive({
  activeRules: 15,
  todayExecutions: 1256,
  errorCount: 3,
  avgResponseTime: 45
})

// 测试表单
const testForm = reactive({
  scenario: 'discount',
  cartAmount: 150,
  itemCount: 3,
  customerType: 'member',
  memberLevel: 'gold',
  categories: ['electronics', 'clothing']
})

// 测试结果
const testResult = ref(null)

// 监控表单
const monitorForm = reactive({
  dateRange: [],
  ruleType: ''
})

// 规则表单
const ruleForm = reactive({
  id: null,
  name: '',
  type: 'discount',
  description: '',
  priority: 1,
  status: 'active',
  conditions: [],
  action: {
    type: 'discount',
    discountAmount: 0,
    discountRate: 9,
    pointsAmount: 0,
    maxDiscount: 0,
    description: ''
  }
})

// 规则数据
const rules = ref([
  {
    id: 1,
    name: '满100减10规则',
    type: 'discount',
    priority: 10,
    status: 'active',
    executionCount: 156,
    successRate: 98,
    lastExecuted: '2024-01-15 14:30:00',
    createTime: '2024-01-01 10:00:00',
    description: '购物车金额满100元减10元',
    conditions: [
      { field: 'cartAmount', operator: 'gte', value: '100', logic: 'and' }
    ],
    action: {
      type: 'discount',
      discountAmount: 10,
      maxDiscount: 0,
      description: '减免10元'
    }
  },
  {
    id: 2,
    name: '会员专享9折规则',
    type: 'member',
    priority: 8,
    status: 'active',
    executionCount: 234,
    successRate: 95,
    lastExecuted: '2024-01-15 14:25:00',
    createTime: '2024-01-01 08:00:00',
    description: '会员客户享受9折优惠',
    conditions: [
      { field: 'customerType', operator: 'eq', value: 'member', logic: 'and' }
    ],
    action: {
      type: 'percentage',
      discountRate: 9,
      maxDiscount: 100,
      description: '9折优惠'
    }
  }
])

// 监控数据
const monitorData = ref([
  {
    ruleName: '满100减10规则',
    executionTime: '2024-01-15 14:30:00',
    executionCount: 156,
    successCount: 153,
    errorCount: 3,
    successRate: 98,
    avgResponseTime: 45,
    totalDiscount: 1530.00
  }
])

// 表单验证规则
const ruleRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入规则描述', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请输入优先级', trigger: 'blur' }
  ]
}

// 计算属性
const filteredRules = computed(() => {
  if (!searchKeyword.value) return rules.value
  return rules.value.filter(rule => 
    rule.name.includes(searchKeyword.value) || 
    rule.description.includes(searchKeyword.value)
  )
})

// 方法
const getRuleTypeColor = (type) => {
  const colorMap = {
    'discount': 'success',
    'gift': 'warning',
    'percentage': 'primary',
    'points': 'info',
    'member': 'danger'
  }
  return colorMap[type] || 'info'
}

const getRuleTypeName = (type) => {
  const nameMap = {
    'discount': '满减规则',
    'gift': '买赠规则',
    'percentage': '折扣规则',
    'points': '积分规则',
    'member': '会员规则'
  }
  return nameMap[type] || type
}

const getStatusColor = (status) => {
  return status === 'active' ? 'success' : 'info'
}

const getStatusName = (status) => {
  return status === 'active' ? '启用' : '停用'
}

const handleTabChange = (tabName) => {
  activeTab.value = tabName
}

const refreshRules = () => {
  ElMessage.success('规则列表已刷新')
}

const showRuleBuilder = () => {
  resetRuleForm()
  ruleBuilderVisible.value = true
  builderTab.value = 'config'
}

const editRule = (rule) => {
  currentRule.value = rule
  Object.assign(ruleForm, rule)
  ruleBuilderVisible.value = true
  builderTab.value = 'config'
}

const viewRule = (rule) => {
  currentRule.value = rule
  ruleDetailVisible.value = true
}

const deleteRule = async (rule) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除规则"${rule.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = rules.value.findIndex(r => r.id === rule.id)
    if (index > -1) {
      rules.value.splice(index, 1)
      ElMessage.success('规则删除成功')
    }
  } catch {
    // 用户取消删除
  }
}

const toggleRuleStatus = (rule) => {
  rule.status = rule.status === 'active' ? 'inactive' : 'active'
  ElMessage.success(`规则已${rule.status === 'active' ? '启用' : '停用'}`)
}

const handleRuleTypeChange = () => {
  // 重置动作配置
  Object.assign(ruleForm.action, {
    type: ruleForm.type,
    discountAmount: 0,
    discountRate: 9,
    pointsAmount: 0,
    maxDiscount: 0,
    description: ''
  })
}

const addCondition = () => {
  ruleForm.conditions.push({
    field: '',
    operator: '',
    value: '',
    logic: 'and'
  })
}

const removeCondition = (index) => {
  ruleForm.conditions.splice(index, 1)
}

const handleActionTypeChange = () => {
  // 根据动作类型重置相关字段
  if (ruleForm.action.type === 'discount') {
    ruleForm.action.discountAmount = 10
  } else if (ruleForm.action.type === 'percentage') {
    ruleForm.action.discountRate = 9
  } else if (ruleForm.action.type === 'points') {
    ruleForm.action.pointsAmount = 100
  }
}

const saveRule = async () => {
  if (!ruleFormRef.value) return
  
  try {
    await ruleFormRef.value.validate()
    saveLoading.value = true
    
    // 模拟保存过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    if (ruleForm.id) {
      // 更新规则
      const index = rules.value.findIndex(r => r.id === ruleForm.id)
      if (index > -1) {
        rules.value[index] = { ...ruleForm }
      }
      ElMessage.success('规则更新成功')
    } else {
      // 创建新规则
      const newRule = {
        ...ruleForm,
        id: Date.now(),
        executionCount: 0,
        successRate: 0,
        lastExecuted: '',
        createTime: new Date().toLocaleString()
      }
      rules.value.unshift(newRule)
      ElMessage.success('规则创建成功')
    }
    
    ruleBuilderVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saveLoading.value = false
  }
}

const resetRuleForm = () => {
  Object.assign(ruleForm, {
    id: null,
    name: '',
    type: 'discount',
    description: '',
    priority: 1,
    status: 'active',
    conditions: [],
    action: {
      type: 'discount',
      discountAmount: 0,
      discountRate: 9,
      pointsAmount: 0,
      maxDiscount: 0,
      description: ''
    }
  })
  ruleFormRef.value?.clearValidate()
}

const testRules = () => {
  activeTab.value = 'test'
}

const handleScenarioChange = () => {
  // 根据测试场景设置默认值
  const scenarios = {
    'discount': { cartAmount: 150, itemCount: 3, customerType: 'guest' },
    'gift': { cartAmount: 200, itemCount: 5, customerType: 'member', memberLevel: 'gold' },
    'percentage': { cartAmount: 100, itemCount: 2, customerType: 'member', memberLevel: 'silver' },
    'points': { cartAmount: 80, itemCount: 2, customerType: 'member', memberLevel: 'normal' },
    'member': { cartAmount: 120, itemCount: 3, customerType: 'member', memberLevel: 'diamond' }
  }
  
  const scenario = scenarios[testForm.scenario]
  if (scenario) {
    Object.assign(testForm, scenario)
  }
}

const executeTest = async () => {
  testLoading.value = true
  
  // 模拟规则引擎执行
  await new Promise(resolve => setTimeout(resolve, 2000))
  
  // 模拟测试结果
  testResult.value = {
    matchedRules: 2,
    totalDiscount: 25.50,
    finalAmount: 124.50,
    appliedRules: [
      {
        name: '满100减10规则',
        type: 'discount',
        discount: 10.00,
        description: '购物车金额满100元减10元'
      },
      {
        name: '会员专享9折规则',
        type: 'member',
        discount: 15.50,
        description: '会员客户享受9折优惠'
      }
    ]
  }
  
  testLoading.value = false
  ElMessage.success('规则测试完成')
}

const resetTestForm = () => {
  Object.assign(testForm, {
    scenario: 'discount',
    cartAmount: 150,
    itemCount: 3,
    customerType: 'member',
    memberLevel: 'gold',
    categories: ['electronics', 'clothing']
  })
  testResult.value = null
}

const showRuleTemplate = () => {
  ElMessage.info('规则模板功能开发中...')
}

const showRuleLogs = () => {
  activeTab.value = 'monitor'
}

const loadMonitorData = () => {
  ElMessage.success('监控数据已更新')
}

const resetMonitorForm = () => {
  Object.assign(monitorForm, {
    dateRange: [],
    ruleType: ''
  })
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.promotion-engine-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.engine-status {
  margin-bottom: 30px;
}

.status-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.status-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.status-icon.active {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.status-icon.success {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.status-icon.warning {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.status-icon.info {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
}

.status-info {
  flex: 1;
}

.status-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.status-label {
  font-size: 14px;
  color: #909399;
}

.rules-section {
  margin-top: 20px;
}

.rules-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.rules-header h4 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.rules-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.test-section {
  padding: 20px 0;
}

.test-result {
  margin-top: 30px;
}

.result-summary {
  margin-bottom: 20px;
}

.result-summary h4 {
  margin: 0 0 16px 0;
  color: #303133;
}

.result-summary p {
  margin: 8px 0;
  color: #606266;
}

.discount-amount {
  color: #67c23a;
  font-weight: 600;
}

.final-amount {
  color: #f56c6c;
  font-weight: 600;
}

.applied-rules {
  margin-top: 20px;
}

.applied-rules h5 {
  margin: 0 0 12px 0;
  color: #303133;
}

.monitor-section {
  padding: 20px 0;
}

.monitor-controls {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.monitor-charts {
  margin-bottom: 20px;
}

.chart-placeholder {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.chart-placeholder p {
  margin: 10px 0 0 0;
  font-size: 14px;
}

.rule-builder {
  padding: 20px 0;
}

.conditions-builder,
.actions-builder {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.conditions-builder h4,
.actions-builder h4 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.condition-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.condition-item {
  padding: 12px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.rule-detail {
  padding: 20px 0;
}

.conditions-display,
.actions-display {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #606266;
  max-height: 200px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .status-content {
    flex-direction: column;
    text-align: center;
  }
  
  .status-icon {
    width: 50px;
    height: 50px;
  }
  
  .rules-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .rules-actions {
    justify-content: center;
  }
  
  .monitor-controls .el-form {
    flex-direction: column;
  }
  
  .monitor-controls .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .condition-item .el-row {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
